<template>
	<div class="zh-carousel-artical">
		<div class="zh-table" v-loading="loading.status" :element-loading-text="loading.txt">
            <el-tabs v-model="editableTabsValue" :before-leave="tabBeforeLeave" type="card" editable @edit="handleTabsEdit">
                <el-tab-pane
                    :key="item.name"
                    v-for="(item, index) in editableTabs"
                    :label="item.titleLocation"
                    :name="item.name">
                    <el-form :rules="rules" :model="item" label-width="100px" ref="ruleForm" v-loading="saveUploading.status" :element-loading-text="saveUploading.txt" v-loading.fullscreen.lock="saveUploading.full">

                        <!-- 文章标题 -->
                        <el-form-item label="文章封面" prop="pic">
                            <div class="pic fl">
                                <div class="show-pic" v-if="item.pic">
                                    <div class="upload-demo fl">
                                        <ul class="el-upload-list el-upload-list--picture-card">
                                            <li tabindex="0" class="el-upload-list__item is-success">
                                                <img :src="BASE_URL+item.pic" alt="轮播图片" class="el-upload-list__item-thumbnail">
                                                <a class="el-upload-list__item-name">
                                                    <i class="el-icon-document"></i>timg.jpg
                                                </a>
                                                <label class="el-upload-list__item-status-label">
                                                    <i class="el-icon-upload-success el-icon-check"></i>
                                                </label>
                                                <i class="el-icon-close"></i>
                                                <!-- <i class="el-icon-close-tip">按 delete 键可删除</i> -->
                                                <span class="el-upload-list__item-actions">
                                                    <span class="el-upload-list__item-preview">
                                                        <i class="el-icon-zoom-in" @click="handlePreview(item.pic)"></i>
                                                    </span>
                                                    <span class="el-upload-list__item-delete">
                                                        <i class="el-icon-delete" @click="deleteImg"></i>
                                                    </span>
                                                </span>
                                            </li>
                                        </ul>
                                        <div tabindex="0" class="el-upload el-upload--picture-card" style="display: none;">
                                            <div class="el-upload-dragger">
                                                <i class="el-icon-upload"></i> 
                                                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                                            </div>
                                            <input type="file" name="file" class="el-upload__input">
                                        </div>
                                    </div>
                                    <!-- <img :src="BASE_URL+item.pic" alt="轮播图片" /> -->
                                </div>    
                                <el-upload
                                    ref="upload"
                                    class="upload-demo upload-hidden fl"
                                    drag
                                    :auto-upload="false"
                                    :action="uploadURL"
                                    :headers="headers"
                                    :on-preview="handlePreview"
                                    :on-success="handleAvatarSuccess"
                                    :on-remove="handleRemove"
                                    :before-remove="beforeRemove"
                                    :before-upload="beforeAvatarUpload"
                                    :on-change="imgChange"
                                    :file-list="fileList"
                                    list-type="picture-card">
                                    <i class="el-icon-upload"></i>
                                    <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                                </el-upload>
                                <el-input class="input-hidden" v-model="item.pic"></el-input>   
                            </div>
                            <p v-if="!item.pic" class="suggest fl">（建议使用比例16:9；像素不低于640*360；jpg，png格式的图片）</p>
                        </el-form-item>
                        <el-form-item label="文章标题" prop="title">
                            <el-input v-model="item.title" placeholder="输入文章标题，最多30个字符" maxLength="30"></el-input>
                        </el-form-item>
                        <el-form-item label="文章内容" prop="content">
                            <el-input class="input-hidden" v-model="item.content"></el-input>
                            <tinymce
                                :id="'id'+index"
                                :plugins="plugins"
                                :other_options="options"
                                :toolbar1="toolbar1"
                                :toolbar2="toolbar2"
                                v-model="item.content"
                                @editorInit="editor"></tinymce>
                               <span class="nubxx" v-if="tinymceNum">{{tinymceNum[index]}} / {{maxLength}}</span>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="submitForm">保存文章</el-button>
                        </el-form-item>
                    </el-form>
                </el-tab-pane>
            </el-tabs>
        </div>
        
        <!-- 裁切文章封面弹窗 -->
        <el-dialog
			title="图片设置"
			:visible.sync="cropperViews"
			width="1000px"
			custom-class="croppering"
			:before-close="clearFilet"
			:close-on-click-modal="false">
			<div class="croppering">
				<div class="cropper">
					<vueCropper
						ref="cropper"
						:img="imgOption.img"
						:outputSize="imgOption.size"
						:outputType="imgOption.outputType"
						:info="true"
						:full="imgOption.full"
						:canMove="imgOption.canMove"
						:canMoveBox="imgOption.canMoveBox"
						:fixedBox="imgOption.fixedBox"
						:original="imgOption.original"
						:autoCrop="imgOption.autoCrop"
						:autoCropWidth="imgOption.autoCropWidth"
						:autoCropHeight="imgOption.autoCropHeight"
						:centerBox="imgOption.centerBox"
						:high="imgOption.high"
						:infoTrue="imgOption.infoTrue"
						:enlarge="imgOption.enlarge">
					</vueCropper>
				</div>
                <div slot="footer" class="dialog-footer cropper_btn">
                    <el-button  @click="clearFilet()">取消</el-button>
                    <el-button type="primary" @click="finish('base64')">确定</el-button>
                </div>
			</div>
		</el-dialog>

        <image-viewer
            v-if="imagePreview.showViewer"
            :initial-index="imageIndex"
            :on-close="closeViewer"
            :url-list="imagePreview.previewSrcList">
        </image-viewer>
    </div>
</template>
<script>
    // 富文本上传图片时另外发请求
    import axios from '../../../tools/axios';
    import tinymce from 'vue-tinymce-editor';
    import { VueCropper }  from 'vue-cropper';
  	export default {
	    data() {
		    return {
                uploadImg: null,
                cropperViews: false, // 是否显示图片裁剪的模态框
                imgOption: { // vue-cropper 参数配置
                    img: '', // 裁剪图片的地址
                    size: 1, // 裁剪生成图片的质量
                    full: false, // 是否输出原图比例的截图
                    outputType: 'png', //输出图片格式
                    canMove: true, //能否拖动图片
                    fixedBox: true, //截图框固定大小
                    original: true, //否显示原始宽高
                    canMoveBox: true,  //能否拖动截图框
                    autoCrop: true, //autoCrop 是否自动生成截图框
                    // 只有自动截图开启 宽度高度才生效
                    autoCropWidth: 880,
                    autoCropHeight: 450,
                    centerBox: false, //截图框是否限制在图片里
                    high: true //是否根据dpr生成适合屏幕的高清图片
                },
                imagePreview: {
                    showViewer: false,
                    previewSrcList: []
                },
                tabsIndex: 0,
                tinymceNum:'',   // 存放每一个富文本统计的字数
                // 加载数据时显示的信息和加载动画
                loading:{
                    status:false,
                    txt:'获取数据...',
                },
                // 发布或者修改文章时的加载信息和动画
                saveUploading:{
                    status: false ,
                    txt:"正在保存...",
                    full:false
                },
                isUpdate:false,     // 每次获取列表信息都会检测，当值为不为false时代表是刚刚保存了修改的文章，false代表页面初始化或者新增文章的操作 
                initList:[],      // 存放从后台获取到的轮播文章初始化信息
                // 新建文章的信息格式
                ruleForm: {
                    titleLocation:'',      // 指tab栏上的标题名，例文章1，文章2
                    pic:'',      // 上传的图片
                    name: '文章 ',
                    title:'',     // 文章的标题
                    content:''     // 文章内容
                },
                rules: {
                    pic: [
                        { required: true, message: '请上传文章封面', trigger: 'change' },
                    ],
                    title: [
                        { required: true, message: '请输入文章标题', trigger: 'change' },
                        // { min: 0, max: 30, message: '最多输入 30 个字符', trigger: 'change' }
                    ],
                    content: [
                        { required: true, message: '请输入文章内容', trigger: 'change' },
                        // { min: 0, max: 5000, message: '最多输入 5000 个字符', trigger: 'change' }
                    ],
                },
                maxLength: 5000,
                uploadURL:this.BASE_URL + '/appapi/resource/res_upload',     // 上传图片的路径
                editableTabsValue: '文章 1',     // 表示当前当前选中的文章
                editableTabs: [      // 此数组的长度等于文章的数量
                   
                ],
                currentContent: null,   // 当前编辑信息的对象
                headers:{     // 请求头信息
                    Authorization: `Bearer ` + this.$g.access_token ,
                    DecisionPlatform :this.$g.decisionPlatform,
                    token : sessionStorage.getItem('token')
                },
                fileList:[],     // 存放上传的文件信息
                previewImgURL: '',
                dialogVisible: false,

                // 以下是富文本的相关参数
                plugins:['paste','fullscreen','link' ,'image'],
                options:{
                    images_upload_handler:this.images_upload_handler,
                    language_url: '/static/tinymce_languages/zh_CN.js',
                    images_upload_url:this.BASE_URL+'/api/alumni/alumniAddPicture',
                    paste_data_images: true,                  // 粘贴的同时能把内容里的图片自动上传，非常强力的功能
                    paste_convert_word_fake_lists: false,     // 插入word文档需要该属性
                    paste_webkit_styles: 'all',
                    paste_merge_formats: true,
                    nonbreaking_force_tab: false,
                    paste_auto_cleanup_on_paste: false,
                    convert_urls: false,
                    font_formats: `
                        微软雅黑=Microsoft YaHei,Helvetica Neue,PingFang SC,sans-serif;
                        宋体='宋体',Helvetica,Arial,sans-serif;
                        仿宋='仿宋',Helvetica,Arial,sans-serif;
                        楷体='楷体',Helvetica,Arial,sans-serif;
                        黑体='黑体',Helvetica,Arial,sans-serif;
                        幼圆='幼圆',Helvetica,Arial,sans-serif;
                        隶书='隶书',Helvetica,Arial,sans-serif;
                        华文新魏='华文新魏',Helvetica,Arial,sans-serif;
                        苹果苹方=PingFang SC,Microsoft YaHei,sans-serif;
                        Arial='Arial',Helvetica,Arial,sans-serif;
                        Verdana=verdana,geneva;
                        Webdings=webdings
                    `,
                },
                toolbar1: 'paste,fullscreen,link,image',
                toolbar2: 'table |insertfile undo redo | formatselect  | fontsizeselect | forecolor backcolor | fontselect bold italic underline strikethrough | alignleft aligncenter alignright alignjustify | outdent indent | link | image | removeformat',
                repeatRequire: false,   // 当点击保存文章后且在请求成功或失败之前此值为true
            }
        },
        created(){
            this.getList(false);
        },
        components: {
            tinymce,
            VueCropper
        },
        watch: {
            // 监听轮播文章进行增减的时候该显示那一篇文章的逻辑
            'editableTabs.length': {
                handler:function(newValue, oldValue){
                    if(oldValue == 0 && newValue >= 1){
                        this.currentContent = this.editableTabs[0];
                    }
                },
                deep:true,
            },
            // 监听当前element的tabs变化时的操作
            'editableTabsValue': {
                handler: function(newVal){
                    var len = newVal.length;
                    var tabsIndex = newVal[len-1];
                    this.tabsIndex = tabsIndex-1;
                    this.currentContent = this.editableTabs[this.tabsIndex];
                },
                immediate: true
            },
            // 监听当前文章被编辑时触发的逻辑
            'currentContent.content': {
                handler: function(newVal, oldVal){
                    if(!newVal) return
                    setTimeout(() => {
                        let body = document.getElementById('id' + this.tabsIndex + '_ifr').contentWindow.document.getElementsByTagName('body')[0].textContent;
                        let newLen = body.length;
                        let oldLen = this.tinymceNum[this.tabsIndex];

                        if (newLen > this.maxLength) {
                            this.$message.warning('内容最大长度不可以超过 ' + this.maxLength + ' 个字');
                            this.currentContent.content = newVal;
                            this.tinymceNum[this.tabsIndex] = oldLen;
                            this.tinymceNum = deep_clone(this.tinymceNum);
                        } else {
                            this.tinymceNum[this.tabsIndex] = newLen;
                            this.tinymceNum = deep_clone(this.tinymceNum);
                        }

                    }, 300);
                },
                immediate: true,
                deep: true
            }
        },
        computed: {
            imageIndex() {
                return this.imagePreview.previewSrcList.indexOf(this.previewImgURL);
            },
        },
		methods: {
            // 更新输入内容的字数
            editor(){
                this.tinymceNum = [];
                this.editableTabs.forEach((item,key)=>{
                    let boby = document.getElementById('id' + key + '_ifr').contentWindow.document.getElementsByTagName('body')[0];
                    boby.innerHTML = item.content

                    this.tinymceNum[key] = boby.textContent.length;
                })

                 // setTimeout(() => {
                 //        let body = document.getElementById('id' + this.tabsIndex + '_ifr').contentWindow.document.getElementsByTagName('body')[0].textContent;
                 //        let newLen = body.replace(/\s/g, '').length;
                 //        let oldLen = this.tinymceNum[this.tabsIndex];

                 //        // 判断邮件长度是否超过 maxLength
                 //        if (newLen > this.maxLength) {
                 //            this.$message.warning('内容最大长度不可以超过 ' + this.maxLength + ' 个字');
                 //            this.tinymceNum[this.tabsIndex] = oldLen;
                 //            // this.ruleForm.content = oldVal;
                 //            this.editableTabs[this.tabsIndex].content = oldVal
                 //        } else {
                 //        this.tinymceNum[this.tabsIndex] = newLen;
                 //        }
                 //    }, 300);
            },
            // 获取轮播文章列表
            getList(status){
                // 当status为true时代表更新数据发起了put请求
                var listParam = {
                    type:1,     // 1：轮播文章；2：普通文章
                    data_type:0,     // 0：没有分页 ； 1：有分页
                    order:'time'     // time：创建时间倒序（适用于后台列表）；top：置顶倒序（适用于前台列表）
                }

                // 显示加载动画
                this.loading.status = true;
                let success = (res=>{
                    // 隐藏加载动画
                    this.loading.status = false;

                    var data = res.data;

                    // 重置返回属性的名字以配合el-tabs使用
                    data.forEach((item,idx)=>{
                        item.titleLocation = this.ruleForm.name + (idx+1);
                        item.name = this.ruleForm.name + (idx+1);
                    })

                    // 每次成功獲取數據前都要重置一下
                    this.initList = [];   

                    if(!status){
                        this.editableTabs = [];
                    }        

                    for(var i=0;i<data.length;i++){
                        this.initList.push(Object.assign({},data[i]));     // 用于储存数据的初始值
                        if(!status){
                            this.editableTabs.push(Object.assign({},data[i]));
                        }
                    }

                    // 判断页面是初始化还是用户点击刷新时做不同的操作
                    if(this.isUpdate){
                        this.editableTabsValue = this.isUpdate
                    }else{
                        this.editableTabsValue = '文章 1';
                    }

                    // 获取添加文章按钮
                    let btn = document.querySelector('.el-tabs__new-tab');

                    // 获取到当前编辑数据数组的长度和初始化数据数组的长度的差值
                    var len = this.editableTabs.length - this.initList.length;

                    if(this.editableTabs.length>=9 && len<=1){
                        btn.style.display = 'none';
                        btn.style.color = '#999';
                    }else{
                        btn.style.display = 'block';
                        btn.style.color = '#399cfd';
                    }

                    this.repeatRequire = false;

                })
                let fail = ( data => {
                    // 隐藏加载动画
                    this.loading.status = false;
                })
                //执行请求，并将回调方法变成config成员以便鉴权过期可以执行
                this.$ajax.get('api/alumni/alumniNews',{params: listParam,func:{success:success,fail:fail}})
            },
            // 新增或者删除文章的相关方法
            handleTabsEdit(targetName, action) {
                var btn = document.querySelector('.el-tabs__new-tab');

                // 获取到当前编辑数据数组的长度和初始化数据数组的长度的差值
                var len = this.editableTabs.length - this.initList.length;

                // 增加文章的方法
                if (action === 'add') {
                    if(len>=1){
                        this.$message.warning('每次只能新增一篇文章');
                        return 
                    }

                    // 声明一个新的变量用于存放初始化的信息格式
                    var newTab = {};

                    Object.assign(newTab,this.ruleForm)

                    // newTabName用于存放tab栏标题名
                    let newTabName = newTab.name + (this.editableTabs.length+1);

                    newTab.titleLocation = newTabName;

                    newTab.name = newTabName;

                    newTab.content = '';

                    this.editableTabs.push(newTab);

                    this.editableTabsValue = newTabName;

                    if(this.editableTabs.length>=9 && len<=1){
                        btn.style.display = 'none';
                    }else{
                        btn.style.display = 'block';
                    }

                    len = this.editableTabs.length - this.initList.length;
                    if(len>=1){
                        btn.style.color = '#999';
                        return 
                    }else{
                        btn.style.color = '#399cfd';
                    }
                }

                // 关闭文章执行的方法
                if (action === 'remove') {
                    // deleteIdx为第几篇文章的序号
                    var deleteIdx = targetName[targetName.length-1] - 1;

                    let yes = ( data => {
                        // 如果存在用户名,则代表文章已经发布，需发起删除文章请求
                        if(this.editableTabs[deleteIdx].username){
                            this.deleteArtical(deleteIdx);
                        }else{
                            this.editableTabs.pop();
                            if(targetName==this.editableTabsValue){
                                this.editableTabsValue = this.editableTabsValue.slice(0,-1) + deleteIdx;
                            }
                        }

                         // 获取添加文章按钮
                        let btn = document.querySelector('.el-tabs__new-tab');

                        // 获取到当前编辑数据数组的长度和初始化数据数组的长度的差值
                        var len = this.editableTabs.length - this.initList.length;

                        if(this.editableTabs.length>=9 && len<=1){
                            btn.style.display = 'none';
                            btn.style.color = '#999';
                        }else{
                            btn.style.display = 'block';
                            btn.style.color = '#399cfd';
                        }

                    })
                    let cancel = ( data => {})
                    this.e_confirm({yes:yes,cancel:cancel,txt:'确定将 '+targetName+' 删除吗？'});
                }

            },
            // 删除文章的方法
            deleteArtical(idx){
                var arrticalId = this.editableTabs[idx].id;
                let success = ( res=>{
                    this.$message.success(res.msg);
                    this.getList();
                })
                let fail = ( res => {
                    // this.$message.error(res.data.msg);
                })
                this.$ajax.delete('api/alumni/alumniNews',{params: {id:arrticalId},func:{success:success,fail:fail}})
            },
            // -------------------------------- 上传组件的相关方法 ↓ --------------------------------
            // 删除上传图片后的回调方法
            handleRemove(file, fileList) {
                // var uploader = document.querySelectorAll('.upload-hidden')[this.tabsIndex];
                // var suggest = document.querySelectorAll('.suggest')[this.tabsIndex];
                // uploader.style.display = 'block';
                // suggest.style.display = 'block';
                // 清除储存的临时图片网络地址
                this.editableTabs[this.tabsIndex].pic = '';
            },
            // 预览上传图片的方法
            handlePreview(url) {
                this.previewImgURL = this.BASE_URL + url;
                this.imagePreview.showViewer = true;
                this.imagePreview.previewSrcList = [this.BASE_URL + url];
            },
            // 关闭预览图片弹窗
            closeViewer() {
                this.imagePreview.showViewer = false;
            },
            // 删除图片的方法
            deleteImg(){
                var currentTab = this.editableTabsValue;
                if(this.editableTabs[this.tabsIndex].file){
                    this.$refs.upload[this.tabsIndex].handleRemove({raw:this.editableTabs[this.tabsIndex].file})
                }else{
                    this.editableTabs[this.tabsIndex].pic = '';
                }
            },
            // 图片上传成功时的回调
            handleAvatarSuccess(file){
                function getData(data){
                    return data.data ? getData(data.data) : data;
                }

                let data = getData(file);
                this.editableTabs[this.tabsIndex].pic = data.file_path;
                
            },
            // 移除上传文件之前做的操作
            beforeRemove(file, fileList) {
                // 若文件格式不符合也会执行此方法，所以做处理避免多余弹窗
                var imgType = file.raw.type.slice(0,5);
                if(imgType!=='image'){
                    return 
                }

                // let yes = ( data => { true } );
                // let cancel = ( data => { false } );
                // this.e_confirm({yes:yes,cancel:cancel,txt:'确定将 '+ file.name +' 删除吗？'});
                // return this.$confirm(`确定移除 ${ file.name }？`);
                return this.$confirm('确定将 '+ file.name +' 删除吗？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                })
            },
            // 上传文件之前做出限制操作的方法
            beforeAvatarUpload(file){
                var imgType = file.type.slice(0,5);
                if(imgType!=='image'){
                    this.$message.error('封面必须是图片格式');
                    return false;
                }

                // 储存器上传文件的信息，以备后面删除时使用
                this.editableTabs[this.tabsIndex].file = file;
            },
            // 文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用	
            imgChange(file, fileList){
                if(file.status == 'ready'){
                    var imgType = file.raw.type.slice(0,5);
                    if(imgType!=='image'){
                        this.$message.error('封面必须是图片格式');
                        return false;
                    }
                    this.uploadImg = file;
                    this.imgOption.img = window.URL.createObjectURL(file.raw);
                    this.cropperViews = true;
                }
            },
            uploadNow(){
                this.$refs.upload[this.tabsIndex].submit();
            },
            //图片裁剪后替换原图片
            finish(type) {
                if (type === 'blob') {
			        this.$refs.cropper.getCropBlob((data) => {
			            this.cropperViews = false;
			        })
			    } else {
			        this.$refs.cropper.getCropData((data) => {
                        function blobToFile(dataurl, filename) { 
                            filename = filename.split(/(.*)\.[^.]+/).join('') + '.png';

                            var arr = dataurl.split(','),
                                mime = arr[0].match(/:(.*?);/)[1],
                                bstr = atob(arr[1]),
                                n = bstr.length,
                                u8arr = new Uint8Array(n);
                            while (n--) {
                                u8arr[n] = bstr.charCodeAt(n);
                            }
                            return new File([u8arr], filename, { type: mime });
                        }

                        this.uploadImg.name = this.uploadImg.name.split(/(.*)\.[^.]+/).join('') + '.png';

                        let file = blobToFile(data, this.uploadImg.name);

                        file.uid = this.uploadImg.raw.uid;
                        this.uploadImg.raw = file;
                        this.cropperViews = false;
                        this.uploadNow();
			        })
			    }
            },
            // -------------------------------- 上传组件的相关方法 ↑ --------------------------------

            //清空上传控件列表的数据
            clearFilet() {
                this.cropperViews = false;
                this.$refs.upload[this.tabsIndex].clearFiles();
                // this.$refs.uploaderImg.uploader.fileList = [];
                // this.$refs.uploaderImg.uploader.files = [];
            },
            // tinyMac富文本图片上传的方法
            // 图片上传三个参数，图片数据，成功时的回调函数，失败时的回调函数
            images_upload_handler (blobInfo, success, failure) {
                if( blobInfo.blob().type.indexOf('image/')  === -1 ){
                    failure('只允许上传图片格式的文件')
                }else if( blobInfo.blob().size >  10240000 ) {
                    failure('图片大小不能超过10M')
               }else{
                    let formData = new FormData();
                        formData.append( 'file', blobInfo.blob() , blobInfo.filename() );

                    function getData(data){
                        return data.data ? getData(data.data) : data;
                    }

                    let succ = ( data => {
                        data = getData(data);
                        success(this.BASE_URL + data)
                    });
                    let fail = ( data => {
                        data = getData(data);
                        failure(data.message)
                    });
                    //******************************TODO 不知为何要重新create*****************//
                    const instance = axios.create({
                        headers:{
                            Authorization:`Bearer ${this.$g.access_token}`,
                            DecisionPlatform :` ${this.$g.access_token}`,
                            token : sessionStorage.getItem('token'),
                        },
                        withCredentials: true,
                     }) 
                    instance.post('api/alumni/alumniAddPicture',formData).then( succ ).catch(fail)
                }
            },  
            tabBeforeLeave(activeName, oldActiveName){
                var oldIdx = oldActiveName.split('').pop() - 1;
                
                // if(this.editableTabs.length>=this.initList.length){
                // 若果离开的tab索引值>=原始数据数组的长度，则执行以下代码
                if(oldIdx>=this.initList.length){
                    if(this.editableTabs.length==this.initList.length){return true;}

                    return this.$confirm(oldActiveName +' 是新建文章且暂未保存，是否保存？', '提示', {
                        confirmButtonText: '保存',
                        cancelButtonText: '暂不保存',
                        type: 'warning'
                    }).then(()=>{
                        // 前往下一个tab
                        this.submitForm(activeName, oldActiveName);
                    }).catch(()=>{
                        // 发送保存请求
                        // 把就就tabName传入验证，当验证不不同不保存时跳转到不验证不成功的页面
                    })
                    // document.querySelector('.el-tabs__new-tab').style.color = '#399cfd';
                }
                else{
                    var oldData = this.initList[oldIdx];
                    var newData = this.editableTabs[oldIdx];

                    var title = oldData.title === newData.title;
                    var pic = oldData.pic === newData.pic;
                    var content = oldData.content === newData.content;

                    if(title && pic && content){
                        return true;
                    }else{
                        switch(false){
                            case title:
                                return this.$confirm(oldActiveName +' 的标题已变更，是否保存？', '提示', {
                                    confirmButtonText: '保存',
                                    cancelButtonText: '暂不保存',
                                    type: 'warning'
                                }).then(()=>{
                                    // 前往下一个tab
                                    this.submitForm(activeName, oldActiveName);
                                })
                            case pic:
                                return this.$confirm(oldActiveName +' 的图片已变更，是否保存？', '提示', {
                                    confirmButtonText: '保存',
                                    cancelButtonText: '暂不保存',
                                    type: 'warning'
                                }).then(()=>{
                                    // 前往下一个tab
                                    this.submitForm(activeName, oldActiveName);
                                })
                            case content:
                                return this.$confirm(oldActiveName +' 的内容已变更，是否保存？', '提示', {
                                    confirmButtonText: '保存',
                                    cancelButtonText: '暂不保存',
                                    type: 'warning'
                                }).then(()=>{
                                    // 前往下一个tab
                                    this.submitForm(activeName, oldActiveName);
                                })
                        }

                    }
                   
                }

            },
            //表单验证
            submitForm(target,oldActive) {
                if(this.repeatRequire){
                    return
                }

                if(!oldActive){
                    target = this.editableTabsValue;
                }

                this.$refs.ruleForm[this.tabsIndex].validate(valid=>{
                    // 当所有必填项都满足ruleForm要求时，valid为true

                    // 获取当前文章的輸入信息
                    var uploadData = this.editableTabs[this.tabsIndex];
                    
                    // 检测文章内容是否为空或者纯空格
                    var content = uploadData.content;
                    // var reg = /<p>(&nbsp;)*(\s&nbsp;)*(&nbsp;)*<\/\s*p>/g
                    // content = content.replace(reg,'')
                    content = content.replace(/\s/g,'')
                    if(!content){
                        this.$message.error('文章内容不能为空')
                        return false;
                    }

                    if(this.tinymceNum[this.tabsIndex] > this.maxLength){
                        this.$message.error('保存失败, 内容最大长度不可以超过 ' + this.maxLength + ' 个字')
                        return false
                    }
                    
                    if(valid){
                        var status = false;
                        this.saveUploading.status = true;
                        this.saveUploading.full = true;
                        this.repeatRequire = true;

                        let success = (data => {
                            this.saveUploading.status = false;
                            this.saveUploading.full = false;
                            this.$message.success(data.msg);
                            // 重新获取最新的轮播文章信息
                            this.getList(status);
                        })
                        let fail = (data => {
                            this.$message.error(data.msg)
                            this.saveUploading.status = false;
                            this.saveUploading.full = false;
                            this.repeatRequire = false;
                        })

                        // 声明一个变量用于存放请求头信息
                        var data = {};
                        data.pic = uploadData.pic;
                        data.title   = uploadData.title ;
                        data.content = uploadData.content;
                        data.type = 1;
                        data.create_id = this.$g.user_id;

                        // 如果存在文章id则发起修改文章请求，反则发起新增文章请求
                        if(uploadData.id){
                            delete data.type;
                            delete data.create_id;
                            data.id = uploadData.id
                            status = true;
                            if(!oldActive){
                                status = false;
                            }
                            
                            this.isUpdate = target;

                            this.$ajax.put('api/alumni/alumniNews',data,{func:{success:success,fail:fail}})
                        }else{
                            this.$ajax.post('api/alumni/alumniNews',data,{func:{success:success,fail:fail}})
                            this.isUpdate = false;
                        }

                    }else{
                        // this.editableTabsValue = oldActive? oldActive : this.editableTabsValue;
                        this.$message.error('文章保存失败')
                    }
                })
            },
        }
    }
</script>
<style lang="scss">
    .zh-carousel-artical {
        .zh-table{
            padding-top:20px;
            .el-tabs{
                min-height:600px;
                border: 1px solid #DDDDDD;
                .el-tabs__header{
                    margin:0;
                    border-bottom:1px solid #DDDDDD;
                    .el-tabs__new-tab{
                        margin-top:9px;
                        margin-right: 26px;
                        width:auto;
                        color:#399cfd;
                        border:0 none;
                        &::after{
                            content:"添加文章";
                            font-size:14px;
                        }
                        &:hover{
                             color:#4c9cfd;;
                        }
                        .el-icon-plus{
                            display:none;
                        }
                    }
                    .el-tabs__nav-wrap{
                        .el-tabs__nav-scroll{
                            .el-tabs__nav{
                                border:0 none;
                                .el-tabs__item{
                                    // color:#999;
                                    &.is-active{
                                        // color:#000;
                                        // background: #fff;
                                        border-bottom:0 none;
                                    } 
                                    &:last-child{
                                        border-right:1px solid #e4e7ed;
                                    }
                                }
                            }
                        }
                    } 
                }
                .el-tabs__content{
                    .el-tab-pane{
                        padding:40px;
                        .el-form{
                            .el-form-item{
                                // .el-form-item__label{

                                // }
                                .el-form-item__content{
                                    .pic{
                                        width:360px;
                                        height:203px;
                                        overflow:hidden;
                                        .pic{
                                            width:100%;
                                            height:100%;
                                            .show-pic{
                                                width:360px;
                                                height:203px;
                                            }
                                        }
                                        .upload-demo{
                                            // margin-left:22px;
                                            width:360px;
                                            height:203px;
                                            overflow:hidden;
                                            .el-upload-list{
                                                .el-upload-list__item{
                                                    margin:0;
                                                    width:100%;
                                                    height:100%;
                                                    .el-upload-list__item-actions{
                                                        span{
                                                            font-size:30px;
                                                            &.el-upload-list__item-delete{
                                                                margin-left:45px;
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                            
                                            .el-upload{
                                                width:100%;
                                                height:100%;
                                                border:0 none;
                                                .el-upload-dragger{
                                                    height:100%;
                                                    .el-icon-upload{
                                                        line-height:120px;
                                                        font-size:120px;
                                                        margin: 23px 0 8px;
                                                        color: #9cd1ff;
                                                    }
                                                    .el-upload__text{
                                                        transform:translateY(-75%);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    .suggest{
                                        margin:180px 0 0 24px;
                                        margin-left:24px;
                                        height:17px;
                                        line-height:17px;
                                        font-size: 12px;
                                        color: #666666;
                                    }
                                    .input-hidden{
                                        width:0;
                                        height:0;
                                        display:none;
                                    }
                                    // 以下是富文本的相关样式
                                    .mce-tinymce.mce-container.mce-panel{
                                        padding-bottom:30px;
                                        .mce-container-body.mce-stack-layout{
                                            .mce-top-part.mce-container.mce-stack-layout-item.mce-first{
                                                .mce-container-body{
                                                    .mce-container.mce-menubar.mce-toolbar.mce-first{
                                                        display:none;
                                                    }
                                                    .mce-toolbar-grp.mce-container.mce-panel.mce-last{
                                                        .mce-container-body.mce-stack-layout{
                                                            .mce-container.mce-toolbar.mce-stack-layout-item.mce-first{
                                                                display:none;
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                        .mce-edit-area.mce-container.mce-panel.mce-stack-layout-item>iframe{
                                            height:445px !important; 
                                        }
                                        .mce-statusbar.mce-container.mce-panel.mce-stack-layout-item.mce-last{
                                            display:none;
                                        }
                                    }
                                    .nubxx{
                                        box-sizing:border-box;
                                        position: absolute;
                                        bottom: 1px;
                                        left:50%;
                                        margin-left:1px;
                                        padding-right:35px;
                                        width:calc(100% - 1px);
                                        height:30px;
                                        background: #F9F9F9;
                                        transform:translateX(-50%);
                                        font-size: 12px;
                                        color: #999;
                                        text-align:right;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        .croppering {
            .cropper {
                height: 500px;
                
                >div{
                    height: 100%;
                }
            }
            
            .dialog-footer {
                padding: 35px 0;
                text-align: center;

                button {
                    padding: 10px 30px;
                }
            }

            .vue-cropper {
                position: relative;
                width: 100%;
                height: 500px;
                box-sizing: border-box;
                user-select: none;
                -webkit-user-select: none;
                -moz-user-select: none;
                -ms-user-select: none;
                direction: ltr;
                touch-action: none;
                text-align: left;
                background-image: url("");
            }

            .cropper-box,
            .cropper-box-canvas,
            .cropper-drag-box,
            .cropper-crop-box,
            .cropper-face {
                position: absolute;
                top: 0;
                right: 0;
                bottom: 0;
                left: 0;
                user-select: none;
            }

            .cropper-box-canvas img {
                position: relative;
                text-align: left;
                user-select: none;
                transform: none;
                max-width: none;
                max-height: none;
            }

            .cropper-box {
                overflow: hidden;
            }

            .cropper-move {
                cursor: move;
            }

            .cropper-crop {
                cursor: crosshair;
            }

            .cropper-modal {
                background: rgba(0, 0, 0, 0.5);
            }
            
            .cropper-view-box {
                display: block;
                overflow: hidden;
                width: 100%;
                height: 100%;
                outline: 1px solid #39f;
                outline-color: rgba(51, 153, 255, 0.75);
                user-select: none;
            }

            .cropper-view-box img {
                user-select: none;
                text-align: left;
                max-width: none;
                max-height: none;
            }

            .cropper-face {
                top: 0;
                left: 0;
                background-color: #fff;
                opacity: 0.1;
            }

            .crop-info {
                position: absolute;
                left: 0px;
                min-width: 65px;
                text-align: center;
                color: white;
                line-height: 20px;
                background-color: rgba(0, 0, 0, 0.8);
                font-size: 12px;
            }

            .crop-line {
                position: absolute;
                display: block;
                width: 100%;
                height: 100%;
                opacity: 0.1;
            }

            .line-w {
                top: -3px;
                left: 0;
                height: 5px;
                cursor: n-resize;
            }

            .line-a {
                top: 0;
                left: -3px;
                width: 5px;
                cursor: w-resize;
            }

            .line-s {
                bottom: -3px;
                left: 0;
                height: 5px;
                cursor: s-resize;
            }

            .line-d {
                top: 0;
                right: -3px;
                width: 5px;
                cursor: e-resize;
            }

            .crop-point {
                position: absolute;
                width: 8px;
                height: 8px;
                opacity: 0.75;
                background-color: #39f;
                border-radius: 100%;
            }

            .point1 {
                top: -4px;
                left: -4px;
                cursor: nw-resize;
            }

            .point2 {
                top: -5px;
                left: 50%;
                margin-left: -3px;
                cursor: n-resize;
            }

            .point3 {
                top: -4px;
                right: -4px;
                cursor: ne-resize;
            }

            .point4 {
                top: 50%;
                left: -4px;
                margin-top: -3px;
                cursor: w-resize;
            }

            .point5 {
                top: 50%;
                right: -4px;
                margin-top: -3px;
                cursor: e-resize;
            }

            .point6 {
                bottom: -5px;
                left: -4px;
                cursor: sw-resize;
            }

            .point7 {
                bottom: -5px;
                left: 50%;
                margin-left: -3px;
                cursor: s-resize;
            }

            .point8 {
                bottom: -5px;
                right: -4px;
                cursor: se-resize;
            }
        }
    }
</style>